#pragma once
#include <thread>
#include <atomic>
#include <vector>
#include <iostream>
#include <filesystem>
#include <fstream>
#include "CFolderUploadLib.h"
#include "CFilestorageClientImpl.h"

namespace fs = std::filesystem;
using OnThreadTaskEnded = std::function<void(int thId)>;

template<typename T>
std::vector<std::vector<T>> splitVector(std::vector<T> v, unsigned int divide)
{
    std::vector<std::vector<T>> result;
    auto total = v.size();
    auto quotient = total / divide;
    auto remainder = total % divide;
    auto index_remain = 0;
    auto add = 0;

    typename std::vector<T>::iterator curPtr = v.begin(), end;
    for (int i = 0; i < divide; i++)
    {
        add = 0;
        if (index_remain < remainder)
        {
            index_remain++;
            add = 1;
        }

        end = curPtr + quotient + add;
        result.push_back(std::vector<T>(curPtr, end));
        curPtr = end;
    }

    return result;
}

class ThreadUpload
{
public:
    ThreadUpload(int id, OnThreadTaskEnded cb);
    ~ThreadUpload();

    void setTasks(std::vector<std::filesystem::path>& files);
    void getStatInfo(UpStatInfo& info);

private:
    void workerThreadFunc();
    bool uploadFile(const std::filesystem::path& filePath);

private:
    int objectId;
    std::thread thread;
    std::atomic<bool> isRun;

    std::vector<std::filesystem::path> newFiles;
    std::atomic<bool> hasNewTask;
    UpStatInfo upStatInfo;
    OnThreadTaskEnded cbTaskEnd;

    //http上传
    CFilestorageClientImpl httpUpClient;
};